package com.tsystems.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tsystems.dao.TrainsEntityManager;



public class ServerIOImpl {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	private final int portNumber = 9090;
	
	public ServerIOImpl() {
		logger.info("Server start");

		Executor executor = Executors.newCachedThreadPool();
		ServerSocket serverSocket = null;

		try {
			try {
				serverSocket = new ServerSocket(portNumber);
				logger.info("Server listen port: {}", portNumber);
			} catch (IOException e) {
				logger.error("Server could't listen on port: {}", portNumber);
				return;
			}

			while (true) {
				Socket socket;
				try {
					socket = serverSocket.accept();
					executor.execute(new ConnectionHandler(socket));
					logger.info("Client connected from address: {}.", socket.getLocalAddress());
				} catch (IOException e) {
					logger.info("Client connection error: {}.", e);
				}
			}
		} finally {
			if (serverSocket != null) {
				try {			
					serverSocket.close();
				} catch (IOException e) {
					logger.error("Can't close server socket: {}", e);
				}
				TrainsEntityManager.getInstance().close();
			}
			
			
			logger.info("Server stop");
		}	
	}


}
